package com.uzai.console.service.merchant.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.enums.MerConfigTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.vo.MerEsOtherDataIndexVo;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DesensitizeUtil;
import com.uzai.console.common.utils.ImgBase64;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.login.Code;
import com.uzai.console.dto.login.RealNameVerificationDto;
import com.uzai.console.dto.login.PasswordUpdateDto;
import com.uzai.console.dto.login.SpecialOperateSendSmsDto;
import com.uzai.console.dto.module.merchant.GuideDto;
import com.uzai.console.dto.module.merchant.MerchantInfoDto;
import com.uzai.console.entity.*;
import com.uzai.console.enums.ContractStatusTypeEnum;
import com.uzai.console.enums.ContractTypeEnum;
import com.uzai.console.enums.MerAccDetailSourceTypeEnum;
import com.uzai.console.enums.SmsType;
import com.uzai.console.jsonvo.contract.ContractSignAddressJson;
import com.uzai.console.jsonvo.merbaseconfig.RealNameVerificationJson;
import com.uzai.console.mapper.*;
import com.uzai.console.service.feign.UzaiContractFeignService;
import com.uzai.console.service.feign.dto.ContractOpeDto;
import com.uzai.console.service.feign.dto.ContractParamDto;
import com.uzai.console.service.feign.dto.ContractRevokeDto;
import com.uzai.console.service.feign.dto.CreateContractDto;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.ratelimit.RatelimitService;
import com.uzai.console.service.sysmaterial.SysMaterialService;
import com.uzai.console.service.tencent.TencentCosService;
import com.uzai.console.vo.feign.contract.ContractSignFlowIdVo;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.module.merchant.GuideVo;
import com.uzai.console.vo.sysmaterial.UploadFileVo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author liuqi
 * @date 2021年08月13日 19:49
 */
@Service
public class MerchantServiceImpl implements MerchantService {

    Logger logger = LoggerFactory.getLogger(MerchantServiceImpl.class);

    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private SysMaterialService sysMaterialService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private KefuUserMapper kefuUserMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private TencentCosService tencentCosService;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private MerAccDetailMapper merAccDetailMapper;

    @Autowired
    private SysContractMapper sysContractMapper;

    @Autowired
    private UzaiContractFeignService uzaiContractFeignService;


    /**
     * 判断运营商是否存在
     *
     * @param mobile
     */
    @Override
    public Merchant getByMobile(String mobile) {

        if (StringUtils.isBlank(mobile) || mobile.length() != 11) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MOBILE_ERROR);
        }
        Merchant merchant = merchantMapper.selectByMobile(mobile);
        if (merchant == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERCHAT_UNREG);
        }

        return merchant;
    }

    /**
     * 查询运营商通过运营商ID
     *
     * @param merId
     */
    @Override
    public Merchant findByMerId(Long merId) {
        return merchantMapper.selectById(merId);
    }

    /**
     * 修改账号信息
     *
     * @param merchantInfoDto
     */
    public void updateLoginInfo(MerchantInfoDto merchantInfoDto, LoginVo loginVo) {
        if (loginVo.getType() != null && loginVo.getType().intValue() == 1) { //子账号登录
            //子账号登录，修改的是子账号信息
            Long accountId = loginVo.getAccountId();
            if (accountId != null) {
                KefuUser kefuUser = kefuUserMapper.selectById(accountId, merchantInfoDto.getMerId());
                if (kefuUser != null) {
                    kefuUser.setName(merchantInfoDto.getName());
                    String headImg = merchantInfoDto.getHeadImg();
                    if (StringUtils.isNotBlank(headImg) && (!headImg.equals(kefuUser.getHeadImg()))) {
                        headImg = headImg.substring(headImg.indexOf("base64,") + 7);
                        InputStream stream = ImgBase64.getFile(headImg);
                        UploadFileVo uploadFileVo = sysMaterialService.upload(merchantInfoDto.getMerId(), stream, IdWorker.get32UUID());
                        kefuUser.setHeadImg(uploadFileVo.getPathUrl());
                    }
                    kefuUserMapper.updateById(kefuUser);
                }
            }
        } else { //主账号登录，修改的是主账号信息
            if (merchantInfoDto.getMerId() == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商ID不能为空");
            }

            if (StringUtils.isBlank(merchantInfoDto.getToken())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商token不能为空");
            }

            Merchant merchant = merchantMapper.selectById(merchantInfoDto.getMerId());

            if (merchant == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该运营商不存在");
            }

            merchant.setName(Tools.getStr(merchantInfoDto.getName()));
            merchant.setWechat(Tools.getStr(merchantInfoDto.getWechat()));
            merchant.setQq(Tools.getStr(merchantInfoDto.getQq()));
            String headImg = merchantInfoDto.getHeadImg();
            if (StringUtils.isNotBlank(headImg) && (!headImg.equals(merchant.getHeadImg()))) {
                headImg = headImg.substring(headImg.indexOf("base64,") + 7);
                InputStream stream = ImgBase64.getFile(headImg);
                UploadFileVo uploadFileVo = sysMaterialService.upload(merchantInfoDto.getMerId(), stream, IdWorker.get32UUID());
                merchant.setHeadImg(uploadFileVo.getPathUrl());
            }

            merchant.setToken(Tools.getStr(merchantInfoDto.getToken()).replace("-", ""));
            merchant.setDevicePwd(Tools.getStr(merchantInfoDto.getDevicePwd()));
            merchantMapper.update(merchant);

            //维护Redis当中的运营商信息
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.MERCHANT.getKey(), merchant.getId()), Tools.getStrEmpty(JSONObject.toJSONString(merchant)));
        }


    }

    /**
     * 敏感操作发送短信验证
     *
     * @param specialOperateSendSmsDto
     * @return
     */
    public void specialOperateSendSms(SpecialOperateSendSmsDto specialOperateSendSmsDto) {

        if (StringUtils.isBlank(specialOperateSendSmsDto.getCode())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "验证码不能为空");
        }

        Merchant merchant = merchantMapper.selectById(specialOperateSendSmsDto.getMerId());

        if (merchant == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        if (specialOperateSendSmsDto.getType() != null) {
            Integer type = specialOperateSendSmsDto.getType();
            if (type.intValue() == SmsType.CMSTYPE_WXCONTACTS_WXID.getValue().intValue()) { //个人微信通讯录显示wxid

                //如果输入的验证码不是系统通用密码，则需要验证
                if (!uzaiConsoleSysConfig.getDefaultPassword().equals(specialOperateSendSmsDto.getCode())) {
                    //获取存在redis中的验证码
                    String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.CMSTYPE_WXCONTACTS_WXID.getDesc(), merchant.getMobile()));
                    //判断验证码是否过期
                    if (StringUtils.isBlank(codeByRedis)) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                    }

                    if (!codeByRedis.equals(specialOperateSendSmsDto.getCode())) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                    }

                    //验证成功，删除验证码
                    redisTemplate.delete(String.format(SmsType.CMSTYPE_WXCONTACTS_WXID.getDesc(), merchant.getMobile()));
                }

                String rediskey = String.format(Const.SmsType.CMSTYPE_WXCONTACTS_WXID_VERIFIED, merchant.getId());
                redisTemplate.opsForValue().set(rediskey, specialOperateSendSmsDto.getCode(), 30, TimeUnit.MINUTES);

            } else if (type.intValue() == SmsType.CMSTYPE_WECHATUSER_WXID.getValue().intValue()) {//个人微信会员详情显示wxid

                Long userId = specialOperateSendSmsDto.getUserId();
                if (userId == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员id");
                }

                //如果输入的验证码不是系统通用密码，则需要验证
                if (!uzaiConsoleSysConfig.getDefaultPassword().equals(specialOperateSendSmsDto.getCode())) {
                    //获取存在redis中的验证码
                    String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.CMSTYPE_WECHATUSER_WXID.getDesc(), merchant.getMobile(), userId));
                    //判断验证码是否过期
                    if (StringUtils.isBlank(codeByRedis)) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                    }

                    //验证码是否正确
                    if (!codeByRedis.equals(specialOperateSendSmsDto.getCode())) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                    }

                    //验证成功，删除验证码
                    redisTemplate.delete(String.format(SmsType.CMSTYPE_WECHATUSER_WXID.getDesc(), merchant.getMobile(), userId));
                }

                String rediskey = String.format(Const.SmsType.CMSTYPE_WECHATUSER_WXID_VERIFIED, merchant.getId(), userId);
                redisTemplate.opsForValue().set(rediskey, specialOperateSendSmsDto.getCode(), 30, TimeUnit.MINUTES);

            } else if (type.intValue() == SmsType.CMSTYPE_REQUESTUSERS_WXID.getValue().intValue()) { //个人微信好友请求显示wxid

                //如果输入的验证码不是系统通用密码，则需要验证
                if (!uzaiConsoleSysConfig.getDefaultPassword().equals(specialOperateSendSmsDto.getCode())) {
                    //获取存在redis中的验证码
                    String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.CMSTYPE_REQUESTUSERS_WXID.getDesc(), merchant.getMobile()));
                    //判断验证码是否过期
                    if (StringUtils.isBlank(codeByRedis)) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                    }
                    //验证码是否正确
                    if (!codeByRedis.equals(specialOperateSendSmsDto.getCode())) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                    }
                    //验证成功，删除验证码
                    redisTemplate.delete(String.format(SmsType.CMSTYPE_REQUESTUSERS_WXID.getDesc(), merchant.getMobile()));
                }
                String rediskey = String.format(Const.SmsType.CMSTYPE_REQESTUSERS_WXID_VERIFIED, merchant.getId());
                redisTemplate.opsForValue().set(rediskey, specialOperateSendSmsDto.getCode(), 30, TimeUnit.MINUTES);
            } else if (type.intValue() == SmsType.CMSTYPE_GROUP_MEMBER_WXID.getValue().intValue()) { //微信群成员显示wxid
                //如果输入的验证码不是系统通用密码，则需要验证
                if (!uzaiConsoleSysConfig.getDefaultPassword().equals(specialOperateSendSmsDto.getCode())) {
                    //获取存在redis中的验证码
                    String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.CMSTYPE_GROUP_MEMBER_WXID.getDesc(), merchant.getMobile()));
                    //判断验证码是否过期
                    if (StringUtils.isBlank(codeByRedis)) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                    }
                    //验证码是否正确
                    if (!codeByRedis.equals(specialOperateSendSmsDto.getCode())) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                    }
                    //验证成功，删除验证码
                    redisTemplate.delete(String.format(SmsType.CMSTYPE_GROUP_MEMBER_WXID.getDesc(), merchant.getMobile()));
                }
                String rediskey = String.format(Const.SmsType.CMSTYPE_GROUP_MEMBER_WXID, merchant.getId());
                redisTemplate.opsForValue().set(rediskey, specialOperateSendSmsDto.getCode(), 30, TimeUnit.MINUTES);
            } else if (type.intValue() == SmsType.CMSTYPE_TAKEBAL_ALIPAY.getValue().intValue()) { //提现列表显示支付宝信息
                //如果输入的验证码不是系统通用密码，则需要验证
                if (!uzaiConsoleSysConfig.getDefaultPassword().equals(specialOperateSendSmsDto.getCode())) {
                    //获取存在redis中的验证码
                    String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.CMSTYPE_TAKEBAL_ALIPAY.getDesc(), merchant.getMobile()));
                    //判断验证码是否过期
                    if (StringUtils.isBlank(codeByRedis)) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                    }
                    //验证码是否正确
                    if (!codeByRedis.equals(specialOperateSendSmsDto.getCode())) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                    }
                    //验证成功，删除验证码
                    redisTemplate.delete(String.format(SmsType.CMSTYPE_TAKEBAL_ALIPAY.getDesc(), merchant.getMobile()));
                }
                String rediskey = String.format(Const.SmsType.CMSTYPE_TAKEBAL_ALIPAY, merchant.getId());
                redisTemplate.opsForValue().set(rediskey, specialOperateSendSmsDto.getCode(), 30, TimeUnit.MINUTES);
            } else if (type.intValue() == SmsType.AMOY_GOLD_APP_SECRET.getValue().intValue()) { //显示淘礼金appsecret
                //如果输入的验证码不是系统通用密码，则需要验证
                if (!uzaiConsoleSysConfig.getDefaultPassword().equals(specialOperateSendSmsDto.getCode())) {
                    //获取存在redis中的验证码
                    String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.AMOY_GOLD_APP_SECRET.getDesc(), merchant.getMobile()));
                    //判断验证码是否过期
                    if (StringUtils.isBlank(codeByRedis)) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                    }
                    //验证码是否正确
                    if (!codeByRedis.equals(specialOperateSendSmsDto.getCode())) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                    }
                    //验证成功，删除验证码
                    redisTemplate.delete(String.format(SmsType.AMOY_GOLD_APP_SECRET.getDesc(), merchant.getMobile()));
                }
                String rediskey = String.format(Const.SmsType.CMSTYPE_AMOY_GOLD_APP_SECRET, merchant.getId());
                redisTemplate.opsForValue().set(rediskey, specialOperateSendSmsDto.getCode(), 30, TimeUnit.MINUTES);
            } else if (type.intValue() == SmsType.CMSTYPE_USER_MOBILE.getValue().intValue()) { //显示会员mobile
                //如果输入的验证码不是系统通用密码，则需要验证
                if (!uzaiConsoleSysConfig.getDefaultPassword().equals(specialOperateSendSmsDto.getCode())) {
                    //获取存在redis中的验证码
                    String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.CMSTYPE_USER_MOBILE.getDesc(), merchant.getMobile()));
                    //判断验证码是否过期
                    if (StringUtils.isBlank(codeByRedis)) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                    }
                    //验证码是否正确
                    if (!codeByRedis.equals(specialOperateSendSmsDto.getCode())) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                    }
                    //验证成功，删除验证码
                    redisTemplate.delete(String.format(SmsType.CMSTYPE_USER_MOBILE.getDesc(), merchant.getMobile()));
                }
                String rediskey = String.format(Const.SmsType.CMSTYPE_USER_MOBILE, merchant.getId());
                redisTemplate.opsForValue().set(rediskey, specialOperateSendSmsDto.getCode(), 30, TimeUnit.MINUTES);
            }
        } else {//复制其他运营商配置方案发送短信验证
            //获取存在redis中的验证码
            String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.SPECIAL_OPERATE.getDesc(), merchant.getMobile()));
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }

            //验证码是否正确
            if (!codeByRedis.equals(specialOperateSendSmsDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(specialOperateSendSmsDto.getCode())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            } else {//验证成功，更新登录信息
                Object loginVoObject = redisTemplate.opsForValue().get(String.format(CacheKey.LOGIN_TOKEN, specialOperateSendSmsDto.getLoginToken()));
                if (loginVoObject != null) {
                    //刷新redis中的登录信息
                    LoginVo loginVO = JSONObject.parseObject(loginVoObject.toString(), LoginVo.class);
                    loginVO.setSendSmsFlag(1);//查询敏感数据授权（已发送短信验证）
                    String token_key = String.format(CacheKey.LOGIN_TOKEN, loginVO.getLoginToken());
                    redisTemplate.opsForValue().set(token_key, Tools.getStrEmpty(JSONObject.toJSONString(loginVO)), CacheKey.LOGIN_TOKEN_EXPIRE, TimeUnit.SECONDS);
                    //删除验证码
                    redisTemplate.delete(String.format(SmsType.SPECIAL_OPERATE.getDesc(), merchant.getMobile()));
                } else {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "登录失效，请重新登录");
                }
            }
        }
    }

    /**
     * 修改功能向导
     *
     * @param guideDto
     */
    public void updateGuide(GuideDto guideDto) {

        if (guideDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商ID不能为空");
        }

        Integer now = DateUtil.getNowTime();

        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(guideDto.getMerId(), MerConfigKeyEnum.GUIDE_CONFIG.getValue());
        if (merBaseConfig != null && StringUtils.isNotBlank(merBaseConfig.getVal())) {
            //查询向导功能配置
            GuideVo guideVo = JSONObject.parseObject(merBaseConfig.getVal(), GuideVo.class);
            //初始化设置
            if (guideDto.getInitSet() != null) {
                guideVo.setInitSet(guideDto.getInitSet());
            }
            //配置方案
            if (guideDto.getConfigPlan() != null) {
                guideVo.setConfigPlan(guideDto.getConfigPlan());
            }
            //机器人
            if (guideDto.getDevice() != null) {
                guideVo.setDevice(guideDto.getDevice());
            }
            //用户类型
            if (guideDto.getUserType() != null) {
                guideVo.setUserType(guideDto.getUserType());
            }
            //个人微信用户
            if (guideDto.getWechatUser() != null) {
                guideVo.setWechatUser(guideDto.getWechatUser());
            }
            //系统素材管理
            if (guideDto.getSysMaterial() != null) {
                guideVo.setSysMaterial(guideDto.getSysMaterial());
            }

            //CMS基础配置
            if (guideDto.getCmsBase() != null) {
                guideVo.setCmsBase(guideDto.getCmsBase());
            }

            //CMS首页配置
            if (guideDto.getCmsHomePage() != null) {
                guideVo.setCmsHomePage(guideDto.getCmsHomePage());
            }

            //CMS个人中心
            if (guideDto.getCmsPersonalCenter() != null) {
                guideVo.setCmsPersonalCenter(guideDto.getCmsPersonalCenter());
            }

            //CMS营销活动
            if (guideDto.getCmsActivity() != null) {
                guideVo.setCmsActivity(guideDto.getCmsActivity());
            }

            //企业微信机器人
            if (guideDto.getWxworkDevice() != null) {
                guideVo.setWxworkDevice(guideDto.getWxworkDevice());
            }

            //企业微信配置方案
            if (guideDto.getWxpubConfig() != null) {
                guideVo.setWxworkConfig(guideDto.getWxpubConfig());
            }

            //企业微信用户
            if (guideDto.getWxworkUser() != null) {
                guideVo.setWxworkUser(guideDto.getWxworkUser());
            }

            //公众号管理
            if (guideDto.getWxpubDevice() != null) {
                guideVo.setWxpubDevice(guideDto.getWxpubDevice());
            }

            //公众号自定义菜单
            if (guideDto.getWxpubCustomizeMenu() != null) {
                guideVo.setWxpubCustomizeMenu(guideDto.getWxpubCustomizeMenu());
            }

            //公众号配置方案
            if (guideDto.getWxpubConfig() != null) {
                guideVo.setWxpubConfig(guideDto.getWxpubConfig());
            }

            //公众号用户
            if (guideDto.getWxpubUser() != null) {
                guideVo.setWxpubUser(guideDto.getWxpubUser());
            }

            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(guideVo)));
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.update(merBaseConfig);
        } else {
            merBaseConfig = new MerBaseConfig();
            merBaseConfig.setId(IdWorker.getId());
            merBaseConfig.setMerId(guideDto.getMerId());
            merBaseConfig.setType(MerConfigTypeEnum.PRODUCTS.getValue());
            merBaseConfig.setKey(MerConfigKeyEnum.GUIDE_CONFIG.getValue());
            merBaseConfig.setCreateTime(now);
            GuideVo guideVo = new GuideVo();
            //初始化设置
            if (guideDto.getInitSet() != null) {
                guideVo.setInitSet(guideDto.getInitSet());
            }
            //配置方案
            if (guideDto.getConfigPlan() != null) {
                guideVo.setConfigPlan(guideDto.getConfigPlan());
            }
            //机器人
            if (guideDto.getDevice() != null) {
                guideVo.setDevice(guideDto.getDevice());
            }
            //用户类型
            if (guideDto.getUserType() != null) {
                guideVo.setUserType(guideDto.getUserType());
            }
            //个人微信用户
            if (guideDto.getWechatUser() != null) {
                guideVo.setWechatUser(guideDto.getWechatUser());
            }

            //系统素材管理
            if (guideDto.getSysMaterial() != null) {
                guideVo.setSysMaterial(guideDto.getSysMaterial());
            }

            //CMS基础配置
            if (guideDto.getCmsBase() != null) {
                guideVo.setCmsBase(guideDto.getCmsBase());
            }

            //CMS首页配置
            if (guideDto.getCmsHomePage() != null) {
                guideVo.setCmsHomePage(guideDto.getCmsHomePage());
            }

            //CMS个人中心
            if (guideDto.getCmsPersonalCenter() != null) {
                guideVo.setCmsPersonalCenter(guideDto.getCmsPersonalCenter());
            }

            //CMS营销活动
            if (guideDto.getCmsActivity() != null) {
                guideVo.setCmsActivity(guideDto.getCmsActivity());
            }

            //企业微信机器人
            if (guideDto.getWxworkDevice() != null) {
                guideVo.setWxworkDevice(guideDto.getWxworkDevice());
            }

            //企业微信配置方案
            if (guideDto.getWxpubConfig() != null) {
                guideVo.setWxworkConfig(guideDto.getWxpubConfig());
            }

            //企业微信用户
            if (guideDto.getWxworkUser() != null) {
                guideVo.setWxworkUser(guideDto.getWxworkUser());
            }

            //公众号管理
            if (guideDto.getWxpubDevice() != null) {
                guideVo.setWxpubDevice(guideDto.getWxpubDevice());
            }

            //公众号自定义菜单
            if (guideDto.getWxpubCustomizeMenu() != null) {
                guideVo.setWxpubCustomizeMenu(guideDto.getWxpubCustomizeMenu());
            }

            //公众号配置方案
            if (guideDto.getWxpubConfig() != null) {
                guideVo.setWxpubConfig(guideDto.getWxpubConfig());
            }

            //公众号用户
            if (guideDto.getWxpubUser() != null) {
                guideVo.setWxpubUser(guideDto.getWxpubUser());
            }

            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(guideVo)));
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.insert(merBaseConfig);
        }
    }

    /**
     * 修改密码
     *
     * @param
     * @return
     */
    public void updatePassword(PasswordUpdateDto passwordUpdateDto, LoginVo loginVo) {

        String mobile = passwordUpdateDto.getMobile();
        if (StringUtils.isBlank(mobile)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机号不能为空");
        }
        String verifyCode = passwordUpdateDto.getVerifyCode();
        if (StringUtils.isBlank(verifyCode)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "验证码不能为空");
        }

        //登录密码
        String password = Tools.getStr(passwordUpdateDto.getPassword());
        if (StringUtils.isBlank(password)) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入登录密码");
        }

        //获取存在redis中的验证码
        String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.PASSWORD.getDesc(), mobile));
        //判断验证码是否过期
        if (StringUtils.isBlank(codeByRedis)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
        }

        //验证码是否正确
        if (!codeByRedis.equals(verifyCode)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
        }

        //删除验证码
        redisTemplate.delete(String.format(SmsType.PASSWORD.getDesc(), mobile));

        if (loginVo.getType() != null && loginVo.getType().intValue() == 1) { //子账号登录
            //子账号登录，修改的是子账号密码
            Long accountId = loginVo.getAccountId();
            if (accountId != null) {
                KefuUser kefuUser = kefuUserMapper.selectById(accountId, loginVo.getMerId());
                if (kefuUser == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该子账号不存在");
                }
                kefuUser.setPwd(password);
                kefuUserMapper.updateById(kefuUser);
            }
        } else { //主账号登录，修改的是主账号密码
            Merchant merchant = merchantMapper.selectById(loginVo.getMerId());
            if (merchant == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该运营商不存在");
            }
            merchant.setCloudPwd(password);
            merchantMapper.update(merchant);
        }
    }

    /**
     * 获取运营商存放会员信息缓存分段名称
     *
     * @param
     * @return
     */
    public String getMechantUserInfoEsName(String esName, Long merId) {
        String esIndexId = "-1";
        String cacheKey = String.format(RedisCacheKeyEnum.MER_ES_INDEX.getKey(), merId);
        Object object = redisTemplate.opsForValue().get(cacheKey);
        //如果缓存没有，从数据库获取
        if (object == null) {
            Merchant merchant = merchantMapper.selectById(merId);
            if (merchant != null) {
                esIndexId = String.valueOf(merchant.getEsIndexId());
                redisTemplate.opsForValue().set(cacheKey, esIndexId);
            }
        } else {
            esIndexId = (String) object;
        }

        if ("-1".equals(esIndexId)) {
            return esName;
        } else {
            return esName + "_" + esIndexId;
        }
    }

    /**
     * 获取运营商存放其他ES索引缓存分段名称
     *
     * @param merId
     * @return
     */
    public String getMechantOtherEsIndexName(String esName, Long merId) {

        //个人微信群成员和企业微信群成员不走分片
        if (EsIndexName.UZAI_WX_GROUP_MEMBER.equals(esName) || EsIndexName.UZAI_WORKWX_GROUP_MEMBER.equals(esName)) {
            return esName;
        }

        //默认配置开关就是ES索引名，个别除外，下面单独处理个别情况
        String otherEsIndex = esName;
        //发单消息ES就取群发消息的配置uzai_group_send_msg
        if (EsIndexName.FD_GROUP_SEND_MSG.equals(esName)) {
            otherEsIndex = EsIndexName.GROUP_SEND_MSG;
        }

        //抖音群ES就取个人微信通讯录分库配置uzai_wx_contacts
        if (EsIndexName.UZAI_TIKTOK_CONVERSATION.equals(esName)) {
            otherEsIndex = EsIndexName.UZAI_WX_CONTACTS;
        }

        Merchant merchant = merchantMapper.selectById(merId);
        if (merchant != null && StringUtils.isNotBlank(merchant.getOtherEsIndex())) {
            try {
                List<MerEsOtherDataIndexVo> merEsOtherDataIndexVoList = JSONObject.parseArray(merchant.getOtherEsIndex(), MerEsOtherDataIndexVo.class);
                if (merEsOtherDataIndexVoList != null && merEsOtherDataIndexVoList.size() > 0) {
                    for (MerEsOtherDataIndexVo merEsOtherDataIndexVo : merEsOtherDataIndexVoList) {
                        if (otherEsIndex.equals(merEsOtherDataIndexVo.getKey())) {
                            if (Tools.getInteger(merEsOtherDataIndexVo.getEnable()).intValue() == 1) { //启用
                                esName = esName + "_" + merEsOtherDataIndexVo.getId();
                            }
                            continue;
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("---运营商信息表中的其他索引分片转JSON失败，error={}", e.getMessage());
            }
        }
        return esName;
    }

    /**
     * 保存运营商实名认证
     *
     * @param
     * @return
     */
    public void realNameVerification(RealNameVerificationDto realNameVerificationDto) {

        if (realNameVerificationDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不能为空");
        }

        Merchant merchant_current = merchantMapper.selectById(realNameVerificationDto.getMerId());
        if (merchant_current == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        String phone = realNameVerificationDto.getPhone();
        if (StringUtils.isBlank(phone)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入手机号");
        }
        String name = realNameVerificationDto.getName();
        if (StringUtils.isBlank(name)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入真实姓名");
        }
        String idCard = realNameVerificationDto.getIdCard();
        if (StringUtils.isBlank(idCard)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入身份证号");
        }
        String verifyCode = realNameVerificationDto.getVerifyCode();
        if (StringUtils.isBlank(verifyCode)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入验证码");
        }

        //如果输入的验证码不是系统通用密码，则需要验证
        if (!uzaiConsoleSysConfig.getDefaultPassword().equals(verifyCode)) {
            //获取存在redis中的验证码
            String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.CMSTYPE_MERCHANT_AUTHENTICATION.getDesc(), phone));
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }

            if (!codeByRedis.equals(verifyCode)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            }
            //验证成功，删除验证码
            redisTemplate.delete(String.format(SmsType.CMSTYPE_MERCHANT_AUTHENTICATION.getDesc(), verifyCode));
        }

        //需要扣费，才能进行实名验证（一个月免费3次）
        //限流判断
        String rateLimitKey = "realNameVerification_key_=" + realNameVerificationDto.getMerId();
        boolean inRateLimit = ratelimitService.inRateLimit(rateLimitKey, 3, 30 * 24 * 3600); //1个月内免费3次
        if (!inRateLimit) {
            //超过3次，需要扣费，一次1元
            //判断余额大小
            Double balance = merchant_current.getBalance();
            if (balance.doubleValue() < 1.0) { //不够支付
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足本次短信费用1.0元，请到【系统设置】/【账号设置】/【账户余额】处充值");
            }
            int now = DateUtil.getNowTime();
            //修改账户余额
            merchant_current.setBalance(balance - 1.0);
            merchant_current.setUpdateTime(now);
            int j = merchantMapper.updateBalance(merchant_current);
            if (j <= 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络异常");
            }
            //添加账户明细
            String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
            MerAccDetail merAccDetail = new MerAccDetail();
            merAccDetail.setId(IdWorker.getId());
            merAccDetail.setMerId(merchant_current.getId());
            merAccDetail.setOperateType(2);//支出
            merAccDetail.setMoney(merchant_current.getBalance());
            merAccDetail.setCgMoney(1.0);
            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.REAL_NAME_VERIFICATION.getId());
            merAccDetail.setSubtype("");
            merAccDetail.setTradeno(trandeNo);
            merAccDetail.setCreateTime(now);
            merAccDetail.setUpdateTime(now);
            merAccDetailMapper.insert(merAccDetail);
        }

        //实名认证
        boolean result = tencentCosService.authentication(phone, name, idCard);
        if (result) { //成功

            RealNameVerificationJson realNameVerificationJson = new RealNameVerificationJson();
            realNameVerificationJson.setIdCard(idCard);
            realNameVerificationJson.setName(name);
            realNameVerificationJson.setPhone(phone);
            //保存到配置方案当中
            MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(realNameVerificationDto.getMerId(), MerConfigKeyEnum.MERCHANT_REAL_NAME_VERIFICATION.getValue());

            Integer now = DateUtil.getNowTime();
            //修改
            if (merBaseConfig != null) {
                //旧身份证号
                String idCard_old = "";
                RealNameVerificationJson realNameVerificationJson_old = JSONObject.parseObject(merBaseConfig.getVal(), RealNameVerificationJson.class);
                if (realNameVerificationJson_old != null) {
                    idCard_old = Tools.getStr(realNameVerificationJson_old.getIdCard());
                }

                //如果包含星星，则不修改
                String idCard_new = Tools.getStr(realNameVerificationDto.getIdCard());
                if (idCard_new.contains("*")) {
                    realNameVerificationJson.setIdCard(idCard_old);
                }

                merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(realNameVerificationJson)));
                merBaseConfig.setUpdateTime(now);
                merBaseConfigMapper.update(merBaseConfig);
            } else { //增加
                merBaseConfig = new MerBaseConfig();
                merBaseConfig.setId(IdWorker.getId());
                merBaseConfig.setMerId(realNameVerificationDto.getMerId());
                merBaseConfig.setType(MerConfigTypeEnum.PRODUCTS.getValue());
                merBaseConfig.setKey(MerConfigKeyEnum.MERCHANT_REAL_NAME_VERIFICATION.getValue());
                merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(realNameVerificationJson)));
                merBaseConfig.setCreateTime(now);
                merBaseConfig.setUpdateTime(now);
                merBaseConfigMapper.insert(merBaseConfig);
            }
        }
    }

    /**
     * 获取运营商实名认证信息
     *
     * @param
     * @return
     */
    public RealNameVerificationJson getRealNameInfo(Long merId) {
        RealNameVerificationJson realNameVerificationJson = null;
        //查询运营商短链接设置信息
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.MERCHANT_REAL_NAME_VERIFICATION.getValue());
        if (merBaseConfig != null) {
            realNameVerificationJson = JSONObject.parseObject(merBaseConfig.getVal(), RealNameVerificationJson.class);
            if (realNameVerificationJson != null) {
                realNameVerificationJson.setIdCard(DesensitizeUtil.around(realNameVerificationJson.getIdCard(), 4, 4));
            }
        }
        Merchant merchant = merchantMapper.selectById(merId);
        realNameVerificationJson.setBalance(merchant.getBalance());
        return realNameVerificationJson;
    }

    @Transactional
    @Override
    public ContractSignAddressJson realNameVerificationAndSign(RealNameVerificationDto realNameVerificationDto) {
        ArrayList<SysContract> contractArrayList = sysContractMapper.selectByMerId(realNameVerificationDto.getMerId());
        List<SysContract> completeContractList = contractArrayList.stream().filter(s -> ContractStatusTypeEnum.COMPLETE.getKey().equals(s.getStatus())).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(completeContractList)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "已签署，请忽重复签署");
        }
        if (realNameVerificationDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不能为空");
        }

        Merchant merchant_current = merchantMapper.selectById(realNameVerificationDto.getMerId());
        if (merchant_current == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        String phone = realNameVerificationDto.getPhone();
        if (StringUtils.isBlank(phone)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入手机号");
        }
        String name = realNameVerificationDto.getName();
        if (StringUtils.isBlank(name)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入真实姓名");
        }
        String idCard = realNameVerificationDto.getIdCard();
        if (StringUtils.isBlank(idCard)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入身份证号");
        }
        String verifyCode = realNameVerificationDto.getVerifyCode();

        if (StringUtils.isBlank(verifyCode)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入验证码");
        }
        //如果输入的验证码不是系统通用密码，则需要验证
        if (!uzaiConsoleSysConfig.getDefaultPassword().equals(verifyCode)) {
            //获取存在redis中的验证码
            String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.CMSTYPE_MERCHANT_AUTHENTICATION.getDesc(), phone));
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }

            if (!codeByRedis.equals(verifyCode)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            }
            //验证成功，删除验证码
            redisTemplate.delete(String.format(SmsType.CMSTYPE_MERCHANT_AUTHENTICATION.getDesc(), verifyCode));
        }


        //  实名签署（一小时限制3次）
        //限流判断
        String rateLimitKey = "realNameContractSign_key_=" + realNameVerificationDto.getMerId();
        boolean inRateLimit = ratelimitService.inRateLimit(rateLimitKey, 3, 3600); //1小时限制3次
        if (!inRateLimit) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "一小时内只能实名3次，请稍后再试！");
        }


        RealNameVerificationJson realNameVerificationJson = new RealNameVerificationJson();
        realNameVerificationJson.setIdCard(idCard);
        realNameVerificationJson.setName(name);
        realNameVerificationJson.setPhone(phone);
        //保存到配置方案当中
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(realNameVerificationDto.getMerId(), MerConfigKeyEnum.MERCHANT_REAL_NAME_VERIFICATION.getValue());

        Integer now = DateUtil.getNowTime();
        //修改
        if (merBaseConfig != null) {
            //旧身份证号
            String idCard_old = "";
            RealNameVerificationJson realNameVerificationJson_old = JSONObject.parseObject(merBaseConfig.getVal(), RealNameVerificationJson.class);
            if (realNameVerificationJson_old != null) {
                idCard_old = Tools.getStr(realNameVerificationJson_old.getIdCard());
            }

            //如果包含星星，则不修改
            String idCard_new = Tools.getStr(realNameVerificationDto.getIdCard());
            if (idCard_new.contains("*")) {
                realNameVerificationJson.setIdCard(idCard_old);
            }

            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(realNameVerificationJson)));
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.update(merBaseConfig);
        } else { //增加
            merBaseConfig = new MerBaseConfig();
            merBaseConfig.setId(IdWorker.getId());
            merBaseConfig.setMerId(realNameVerificationDto.getMerId());
            merBaseConfig.setType(MerConfigTypeEnum.PRODUCTS.getValue());
            merBaseConfig.setKey(MerConfigKeyEnum.MERCHANT_REAL_NAME_VERIFICATION.getValue());
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(realNameVerificationJson)));
            merBaseConfig.setCreateTime(now);
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.insert(merBaseConfig);
        }


        // 查询是否有签署中的合同
        SysContract contract = sysContractMapper.selectByType(realNameVerificationDto.getMerId(), ContractStatusTypeEnum.UNDER_SIGNATURE.getKey());
        ContractSignAddressJson contractSignAddressJson = new ContractSignAddressJson();
        if (contract != null) {
            // 有签署中的合同 直接作废 重新生成新合同;
            sysContractMapper.updateBySingFlowId(contract.getSignFlowId(), ContractStatusTypeEnum.CANCEL.getKey());
            ContractRevokeDto contractRevokeDto = new ContractRevokeDto();
            contractRevokeDto.setSignFlowId(contract.getSignFlowId());
            uzaiContractFeignService.revokeContract(contractRevokeDto);
        }
        // 远程创建合同
        CreateContractDto createContractDto = new CreateContractDto();
        ContractParamDto contractParamDto = new ContractParamDto();
        contractParamDto.setPhone(realNameVerificationDto.getPhone());
        contractParamDto.setName(realNameVerificationDto.getName());
        createContractDto.setComponents(contractParamDto);
        createContractDto.setSignerId(realNameVerificationDto.getMerId().toString());
        createContractDto.setContractType(ContractTypeEnum.REBATE_SYSTEM_REGISTRATION.getKey());
        // 获取 合同签署Id
        UzaiRespVo<ContractSignFlowIdVo> uzaiRespVo = uzaiContractFeignService.createContract(createContractDto);
        if (uzaiRespVo.getCode() != 200 && uzaiRespVo.getData() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "合同创建失败");
        }
        String signFlowId = uzaiRespVo.getData().getSignFlowId();
        // 保存合同
        SysContract sysContract = new SysContract();
        sysContract.setId(IdWorker.getId());
        sysContract.setMerId(realNameVerificationDto.getMerId());
        sysContract.setStatus(ContractStatusTypeEnum.UNDER_SIGNATURE.getKey());
        sysContract.setContractType(ContractTypeEnum.REBATE_SYSTEM_REGISTRATION.getKey());
        sysContract.setCreateTime(now);
        sysContract.setUpdateTime(now);
        sysContract.setSignFlowId(signFlowId);
        ContractOpeDto contractOpeDto = new ContractOpeDto();
        contractOpeDto.setSignFlowId(signFlowId);
        // http://test.52youzai.net/api/console/romoteApi/callback/updateContractAndReturn
        contractOpeDto.setRedirectUrl(uzaiConsoleSysConfig.getContractSignCallbackUrl() + signFlowId);

        try {
            // 防止获取
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        UzaiRespVo<ContractSignAddressJson> contractSignUrl = uzaiContractFeignService.getContractSignUrl(contractOpeDto);
        if (contractSignUrl.getCode() == 200 && contractSignUrl.getData() != null) {
            contractSignAddressJson = contractSignUrl.getData();
            sysContract.setSignUrl(contractSignAddressJson.getUrl());
        }
        sysContractMapper.insert(sysContract);

        // 进行扣费


        String count = (String) redisTemplate.opsForValue().get(String.format(CacheKey.REQUEST_OVER_MAXCOUNT_SIGN_MERID, merchant_current.getId()));
        // 如果次数为3次 则要扣费
        if (count != null && count.equals("3")) {
            //判断余额大小
            Double balance = merchant_current.getBalance();
            if (balance.doubleValue() < 1) { //不够支付
                contractSignAddressJson.setUrl(""); // 防止余额不够用户直接通过返回的url去签署
                contractSignAddressJson.setStatus(1);
                contractSignAddressJson.setMsg("余额不足请到【系统设置】/【账号设置】/【账号信息】处充值");
                return contractSignAddressJson;
            }
            int nowTime = DateUtil.getNowTime();
            //修改账户余额
            merchant_current.setBalance(balance - 1);
            merchant_current.setUpdateTime(nowTime);
            int j = merchantMapper.updateBalance(merchant_current);
            if (j <= 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络异常");
            }
            //添加账户明细
            String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
            MerAccDetail merAccDetail = new MerAccDetail();
            merAccDetail.setId(IdWorker.getId());
            merAccDetail.setMerId(merchant_current.getId());
            merAccDetail.setOperateType(2);//支出
            merAccDetail.setMoney(merchant_current.getBalance());
            merAccDetail.setCgMoney(1.0);
            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.REAL_NAME_CONTRACT_SIGN.getId());
            merAccDetail.setSubtype("");
            merAccDetail.setTradeno(trandeNo);
            merAccDetail.setCreateTime(nowTime);
            merAccDetail.setUpdateTime(nowTime);
            merAccDetailMapper.insert(merAccDetail);
            contractSignAddressJson.setStatus(0);
            return contractSignAddressJson;


        }
        contractSignAddressJson.setStatus(0);
        redisTemplate.opsForValue().set(String.format(CacheKey.REQUEST_OVER_MAXCOUNT_SMS_MERID, merchant_current.getId()), count == null ? 1 : Integer.valueOf(count) + 1);
        return contractSignAddressJson;


    }
}
